package cn.edu.jsu.zjj.controller;

import cn.edu.jsu.zjj.annotation.Type;
import cn.edu.jsu.zjj.common.result.PageResult;
import cn.edu.jsu.zjj.common.result.Result;
import cn.edu.jsu.zjj.constant.MessageConstant;
import cn.edu.jsu.zjj.exception.BaseException;
import cn.edu.jsu.zjj.model.dto.docu.DocuInduceRequest;
import cn.edu.jsu.zjj.model.entity.DocuInduce;
import cn.edu.jsu.zjj.model.utils.ZipUtils;
import cn.edu.jsu.zjj.service.DocuInduceService;
import cn.edu.jsu.zjj.service.UserService;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/docu-induce")
@Api(tags = "资料规范相关接口")
@Slf4j
public class DocuInduceController {

    @Autowired
    private DocuInduceService docuInduceService;
    private UserService userService;

    @Type("查询资料规范")
    @ApiOperation("查询资料规范")
    @GetMapping
    public Result<PageResult> query(@ModelAttribute DocuInduceRequest docuInduceRequest) {

        long size = docuInduceRequest.getPageSize();
        int current = docuInduceRequest.getCurrent();

        String userMajorId = docuInduceRequest.getMajorId();

        // 调用服务层方法进行查询
        Page<DocuInduce> result = docuInduceService.queryDocuInduce(new Page<>(current, size), docuInduceRequest.getName(), userMajorId);
        return Result.success(new PageResult(result.getTotal(), result.getRecords()));
    }

    @Type("查询资料规范")
    @ApiOperation("查询资料规范")
    @GetMapping("/{id}")
    public Result query(@PathVariable("id") Long id) {
        DocuInduce docuInduce = docuInduceService.getById(id);
        return Result.success(docuInduce);
    }


    /**
     * 根据id下载附件
     *
     * @param id
     * @return
     */
    @Type("查询资料规范")
    @ApiOperation("查询资料规范")
    @PostMapping("/download/{id}")
    public Result download(@PathVariable("id") Long id, HttpServletResponse response) {
        LambdaQueryWrapper<DocuInduce> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DocuInduce::getId, id);
        queryWrapper.eq(DocuInduce::getIsDeleted, 0);
        DocuInduce docuInduce = docuInduceService.getOne(queryWrapper);
        String fileUrl = docuInduceService.getOne(queryWrapper) == null ? "" : docuInduce.getFileUrl();
        try {
            // 下载文件
            String fileName = docuInduce.getFileName();

            // 确保文件名不为空
            if (fileName == null || fileName.isEmpty()) {
                return Result.error("文件名为空，无法下载");
            }

            // 检查文件名中是否有后缀
            int lastIndexOfDot = fileName.lastIndexOf(".");
            if (lastIndexOfDot == -1) {
                // 如果没有后缀
                return Result.error("文件名中没有后缀，无法下载");
            } else {
                // 如果有后缀，正常处理
                String excelName = fileName.substring(0, lastIndexOfDot);
                String suffix = fileName.substring(lastIndexOfDot + 1);

                ZipUtils.urlToByte(fileUrl);
                byte[] urlBytes = ZipUtils.urlBytes;
                ZipUtils.send(urlBytes, response, excelName, suffix);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return Result.success(docuInduce);
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @Type("根据id删除")
    @ApiOperation("根据id删除")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Long id) {
        DocuInduce docuInduce = new DocuInduce();
        docuInduce.setId(id);
        docuInduce.setIsDeleted(true);
        boolean result = docuInduceService.updateById(docuInduce);
        if (result) {
            return Result.success();
        }
        return Result.error("删除失败");
    }

    /**
     * 新增资料归纳
     *
     * @param docuInduce
     * @return
     */
    @Type("新增资料规范")
    @ApiOperation("新增资料规范")
    @PostMapping
    public Result add(@RequestBody DocuInduce docuInduce) {
        // 判断必填参数
        if (StringUtils.isEmpty(docuInduce.getName())) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }

        Map<String, String> res = CommonController.res;
        docuInduce.setFileName(res.get("fileName"));
        docuInduce.setFileUrl(res.get("fileUrl"));
        docuInduce.setUserId(userService.getLoginUser().getId());
        docuInduce.setUserName(userService.getLoginUser().getName());
        docuInduce.setCreateTime(new Date());
        docuInduce.setUpdateTime(new Date());
        // 新增
        boolean result = docuInduceService.save(docuInduce);
        if (result) {
            return Result.success();
        }
        return Result.error("新增失败");
    }

    /**
     * 修改资料规范
     *
     * @param docuInduce
     * @return
     */
    @Type("修改资料规范")
    @ApiOperation("修改资料规范")
    @PutMapping
    public Result put(@RequestBody DocuInduce docuInduce) {
        // 判断必填参数
        if (StringUtils.isEmpty(docuInduce.getName()) || StringUtils.isEmpty(docuInduce.getFileUrl())) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }

        docuInduce.setUpdateTime(new Date());
        docuInduce.setFileUrl(docuInduce.getFileUrl());

        // 新增
        boolean result = docuInduceService.saveOrUpdate(docuInduce);
        if (result) {
            return Result.success();
        }
        return Result.error("修改失败");
    }
}
